//
//  UserCenterViewController.m
//  CoolTennisBall
//
//  Created by Coollang on 16/8/22.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "UserCenterViewController.h"
#import "UserSettingController.h"
#import "UIView+Frame.h"
#import "UserDataController.h"
#import "UserCareerController.h"
#import "UserZhuangBeiController.h"
#import <SDWebImage/UIButton+WebCache.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "UIImage+ImageCompose.h"
#import "UserHomeModel.h"
#import "CoollangTennisBall-Swift.h"
#import "UIImageView+CM_ShowImage.h"
#import "UserCustomScrollView.h"
#import "UIImageView+LBBlurredImage.h"
#import "UIImage+ImageEffects.h"

static NSString * const kSettingSegue = @"UserSettingSegue";
static NSString * const kDataSegue = @"UserDataSegue";
static NSString * const kCareerSegue = @"UserCareerSegue";
static NSString * const kZhuangBeiSegue = @"UserZhuangBeiSegue";


 NSString * const kUserinfroChangeNotification = @"kUserinfroChangeNotification";

@interface UserCenterViewController ()
@property (weak, nonatomic) IBOutlet UserCustomScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *headView;
@property (weak, nonatomic) IBOutlet UIImageView *headBgImageView;

@property (weak, nonatomic) IBOutlet UIButton *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UIButton *locationButton; // 用户位置

@property (weak, nonatomic) IBOutlet UIScrollView *contenetScrollView;

@property (weak, nonatomic) IBOutlet UIButton *userDataButton;
@property (weak, nonatomic) IBOutlet UIButton *userEquipButton;
@property (weak, nonatomic) IBOutlet UIButton *userCareerButton;

@property (nonatomic, strong) UIButton *currentButton;
@property (nonatomic, weak) UIVisualEffectView *visualView;
@property (nonatomic, weak) UIView *blurView;

@property (strong, nonatomic) UserHomeModel *userModel;

@end

@implementation UserCenterViewController {
    BOOL _showUserInfo;
    UserCareerController *_careerVc;
    UserDataController *_dataVc;
    UserZhuangBeiController *_zhuangBeiVc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    adjustsScrollViewInsets_NO(self.scrollView, self);
    
    [self channelButtonClick:self.userDataButton];
 
    self.headImageView.layer.cornerRadius = 50;
    self.headImageView.layer.borderWidth = 3;
    self.headImageView.layer.borderColor = [UIColor colorWithWhite:1 alpha:0.2].CGColor;
    self.headImageView.layer.masksToBounds = YES;
    //self.headImageView.imageView.contentMode = UIViewContentModeScaleToFill;
     self.headImageView.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [self layoutUserInfo];
    
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.bounces = NO;
    self.contenetScrollView.bounces = NO;
    self.contenetScrollView.scrollEnabled = NO;
    
    [self configureLocalization];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:kSettingSegue]) {
        _showUserInfo = YES;
    }else if ([segue.identifier isEqualToString:kDataSegue]){
        _dataVc = segue.destinationViewController;
    }else if ([segue.identifier isEqualToString:kCareerSegue]){
        _careerVc = segue.destinationViewController;
    }else if ([segue.identifier isEqualToString:kZhuangBeiSegue]){
        _zhuangBeiVc = segue.destinationViewController;
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self addBrulViewIsBlur:NO];
}
- (void)configureLocalization {
    [self.userDataButton setTitle:NSLocalizedString(@"User.Data", @"数据") forState:UIControlStateNormal];
    [self.userCareerButton setTitle:NSLocalizedString(@"Career", @"生涯") forState:UIControlStateNormal];
    [self.userEquipButton setTitle:NSLocalizedString(@"User.Equipment", @"装备") forState:UIControlStateNormal];
}

#pragma mark - 点击事件
- (IBAction)channelButtonClick:(UIButton *)sender {
    
    self.currentButton.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.4];
    sender.backgroundColor = [UIColor colorWithHex:0x25c9ad alpha:0.4];
    self.currentButton = sender;
    
    self.contenetScrollView.contentOffset = CGPointMake((sender.tag - 50) * kYFScreenWidth, 0);
}
- (IBAction)headImageViewClick:(UIButton *)sender {
    [sender.imageView showImage];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [self getUserHomeInfo];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (!_showUserInfo) {
        [self.navigationController setNavigationBarHidden:NO animated:NO];
    }
}

#pragma mark - Notification
- (void)registerNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(layoutUserInfo) name:kUserinfroChangeNotification object:nil];
}

#pragma mark - getNetworkData
- (void)getUserHomeInfo {
    User *user = [User getLastUser];
    UserInforItem *item = [user userInforItem];
    
    YFUserApi *api = [YFUserApi requestGetUserDataWithReqType:kUserGetHomeDataApi];
    
    [[YFNetworkingService sharedInstance] sendRequest:api callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            UserHomeModel *model = [[UserHomeModel alloc] initWithDictionary: [api responseInfo]];
            self.userModel = model;
            if ([model.readMedalsString length] > 0) {
                YFUserApi *medalApi = [YFUserApi initWithReadMedalsString:model.readMedalsString];
                [[YFNetworkingService sharedInstance] sendRequest:medalApi callback:^(BOOL success, id result, NSError *error) {
                    if (success) {
                        [self updateUI];
                    }
                }];
            } else {
                [self updateUI];
            }
        }
    }];
}

#pragma mark - 更新界面
- (void)layoutUserInfo{
    User *user = [User getLastUser];
    UserInforItem *item = [user userInforItem];
    
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:item.headIconPath] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"competition_icon_defaulImage"]];
    
    if ([self locationKeyPathIsEqualService:self.userModel.headIcon]) {
        
        NSString *imagefilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:self.userModel.headIcon.lastPathComponent];
        [self.headBgImageView sd_setImageWithURL:[NSURL fileURLWithPath:imagefilePath] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            NSLog(@"%@",error);
        }];
        
        [self.headBgImageView sd_setImageWithURL:[NSURL fileURLWithPath:imagefilePath] placeholderImage:nil];
    }else {
        [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:self.userModel.headIcon] options:SDWebImageDownloaderUseNSURLCache | SDWebImageDownloaderLowPriority progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (image != nil) {
                // 将高斯模糊图片缓存到沙盒
                [self.headBgImageView setImageToBlur:image blurRadius:30 completionBlock:^{
                    [self saveGaosiMohuImage:self.headBgImageView.image keyPath:self.userModel.headIcon];
                }];
                
            }
        }];
        
    }
    
    [self.locationButton setTitle:item.location forState:UIControlStateNormal];
    self.nameLabel.text = item.name;
}

- (void)updateUI {
    self.nameLabel.text = self.userModel.userName;
    [self.locationButton setTitle:self.userModel.address forState:UIControlStateNormal];
    
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:self.userModel.headIcon] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"competition_icon_defaulImage"]];
    
    __weak typeof(self) weakSelf = self;
    
    if ([self locationKeyPathIsEqualService:self.userModel.headIcon]) {
        
         NSString *imagefilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:self.userModel.headIcon.lastPathComponent];
        [self.headBgImageView sd_setImageWithURL:[NSURL fileURLWithPath:imagefilePath] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            NSLog(@"%@",error);
            self.headBgImageView.image = image;
        }];
        
        [self.headBgImageView sd_setImageWithURL:[NSURL fileURLWithPath:imagefilePath] placeholderImage:nil];
    }else {
        [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:self.userModel.headIcon] options:SDWebImageDownloaderUseNSURLCache|SDWebImageDownloaderLowPriority progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (image != nil) {
                
                [weakSelf.headBgImageView setImageToBlur:image blurRadius:30 completionBlock:^{
                    [weakSelf saveGaosiMohuImage:weakSelf.headBgImageView.image keyPath:self.userModel.headIcon];
                }];
                
            }
        }];
    }
    
    _careerVc.userModel = self.userModel;
    [_careerVc.tableView reloadData];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"UpDataUserCareerData" object:nil];
}

- (void)saveGaosiMohuImage:(UIImage *)image keyPath:(NSString *)keyPath {
    
    NSString *locationKeyPath = [[NSUserDefaults standardUserDefaults] objectForKey:@"gaoSiMohuImage"];
    if (![keyPath isEqualToString:locationKeyPath]) {
        // 保存
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
        NSString *imagefilePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        
        // 先删除之前的图片
        if (locationKeyPath != nil) {
            [self removeGaosimohuImage:locationKeyPath.lastPathComponent];
        }
        BOOL writeSucc = [imageData writeToFile:[imagefilePath stringByAppendingPathComponent:keyPath.lastPathComponent] atomically:YES];
        NSLog(@"%zd",writeSucc);
        [[NSUserDefaults standardUserDefaults] setObject:keyPath forKey:@"gaoSiMohuImage"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (void)removeGaosimohuImage:(NSString *)lastComPath {
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:lastComPath];
    if ([manager fileExistsAtPath:filePath]) {
        NSError *error;
        [manager removeItemAtPath:filePath error:&error];
        if (!error) {
            NSLog(@"高斯模糊图片删除成功");
        }
    }
}

- (BOOL)locationKeyPathIsEqualService:(NSString *)keyPath {
    NSString *locationKeyPath = [[NSUserDefaults standardUserDefaults] objectForKey:@"gaoSiMohuImage"];
    if ([keyPath isEqualToString:locationKeyPath]) {
        return YES;
    }else {
        return NO;
    }
}

#pragma mark - 添加毛玻璃效果
- (void)addBrulViewIsBlur:(BOOL)isBlur {

    if (isBlur) {
        [self.blurView removeFromSuperview];
        self.blurView = nil;
        if (self.visualView == nil ) {
            UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
            
            UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithEffect:effect];
            self.visualView = visualView;
            [self.headBgImageView layoutIfNeeded];
            visualView.frame = self.headBgImageView.bounds;
            //visualView.alpha = 0.3;
            visualView.alpha = 0.3;
            [self.headView insertSubview:visualView aboveSubview:self.headBgImageView];
        }
    }else {
        [self.visualView removeFromSuperview];
        self.visualView = nil;
        if (self.blurView == nil) {
            [self.headBgImageView layoutIfNeeded];
            UIView *blurView = [[UIView alloc] initWithFrame:self.headBgImageView.bounds];
            blurView.backgroundColor = [UIColor blackColor];
            blurView.alpha = 0.1;
            [self.headView insertSubview:blurView aboveSubview:self.headBgImageView];
            self.blurView = blurView;
        }
    }
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//  2.处理顶部
    if (self.scrollView == scrollView) {
        CGFloat present = kYFScreenWidth < 375 ? 0.5 : 0.45;
        CGFloat scale = scrollView.contentOffset.y / ( scrollView.contentSize.height - kYFScreenHeight + kTabBarHeight);
        self.headImageView.transform = CGAffineTransformMakeScale(1 - scale * present, 1 - scale * present);
        self.headImageView.transform = CGAffineTransformTranslate(self.headImageView.transform, 0, scrollView.contentOffset.y * (-present) + scale*(-20));
        
        if (scale > 0.7) {
            self.nameLabel.alpha = 0;
            self.locationButton.alpha = 0;
        }else {
            self.nameLabel.alpha = 1 - scale;
            self.locationButton.alpha = 1- scale;
        }
    }
}

@end
